package com.lagou.edu.demo.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


@Component
public class LocalBeanProcessor implements BeanPostProcessor {

    @Autowired
    private DefaultListableBeanFactory defaultListableBeanFactory;

    private String targetBeanName = "hikariDataSource";

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (StringUtils.endsWithIgnoreCase(beanName, targetBeanName)) {
            boolean containsBean = defaultListableBeanFactory.containsBean(targetBeanName);
            if (containsBean) {
                //移除bean的定义和实例
                defaultListableBeanFactory.removeBeanDefinition(targetBeanName);
            }
            //注册新的bean定义和实例
            defaultListableBeanFactory.registerBeanDefinition(targetBeanName,
                    BeanDefinitionBuilder.genericBeanDefinition(HikariDataSource.class).getBeanDefinition());
            bean = null;
            return new HikariDataSource();
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}